﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcEnrollment.Models;
using System.Xml;

namespace MvcEnrollment.Controllers
{
    public class CourseController : Controller
    {
        //private CourseDBContext db = new CourseDBContext();
        private EnrollmentEntities1 db = new EnrollmentEntities1();

        //display next cut off date for courses from ICI
        public ActionResult CutoffDate(int id = 0)
        {
            Course course = db.Courses.Find(id);
            if (course == null)
            {
                return HttpNotFound();
            }
            if (course.Course_Provider.Equals("International Career Institute (ICI)"))
            {
                int interval = ((int)DayOfWeek.Friday + 7 - (int)DateTime.Today.DayOfWeek) % 7;
                DateTime nextFriday = DateTime.Today.AddDays(interval);
                ViewData["nextFriday"] = nextFriday.Date.ToString("dd MMM yyyy");
                return View();
            }
            return null;
        }

        //render payment details for ICI and careerline
        public ActionResult PaymentOptions(int id = 0)
        {
            Course course = db.Courses.Find(id);
            if (course == null)
            {
                return HttpNotFound();
            } 
            ViewData["courseId"] = course.Course_Id;
            ViewData["courseName"] = course.Course_Name;
            ViewData["institution"] = course.Course_Provider;
            Course_Price fullPrice = getFullPrice(id);
            if (fullPrice != null)
            {
                ViewData["FullPrice"] = fullPrice.Total_Price;
                ViewData["FPID"] = fullPrice.Course_Price_Id;
                if (fullPrice.Discount != 0)
                {
                    ViewData["FAddInfo"] = "with" + fullPrice.Discount + "% off discount";
                }
            }
            Course_Price monthPrice = getMonthPrice(id);
            if (monthPrice != null)
            {
                ViewData["MonthPrice"] = monthPrice.Recurring_Amount;
                ViewData["MonthDuration"] = String.Format("{0:n0}", monthPrice.Total_Recurrings);
                ViewData["MPID"] = monthPrice.Course_Price_Id;
                if (monthPrice.Discount != 0)
                {
                    ViewData["MAddInfo"] = "with" + monthPrice.Discount + "% off discount";
                }
            }
            Course_Price weekPrice = getWeekPrice(id);
            if (weekPrice != null)
            {
                ViewData["WeekPrice"] = weekPrice.Recurring_Amount;
                ViewData["WeekDuration"] = String.Format("{0:n0}", weekPrice.Total_Recurrings);
                ViewData["WPID"] = weekPrice.Course_Price_Id;
                if (weekPrice.Discount != 0)
                {
                    ViewData["WAddInfo"] = "with" + weekPrice.Discount + "% off discount";
                }
            }
            if (course.Course_Provider.Equals("Online Courses Australia"))
            {
                return PartialView("PaymentWithoutMonth", id);
            }
            return View();
        }

        //render payment details for Online Courses Australia, no month payment displayed
        public ActionResult PaymentWithoutMonth(int id = 0)
        {
            return View();
        }
        
        //get fully installment details
        public Course_Price getFullPrice(int courseId = 0)
        {
            Course_Price price = new Course_Price();
            var course_price = from p in db.Course_Price
                          select p;
            if (courseId != 0)
            {
                course_price = course_price.Where(s => s.Course_Id.Equals(courseId));
                price = course_price.SingleOrDefault(s => s.Payment_Type.Equals("Fully"));
            }
            return price;
        }

        //get monthly installment details
        public Course_Price getMonthPrice(int courseId = 0)
        {
            Course_Price price = new Course_Price();
            var course_price = from p in db.Course_Price
                          select p;
            if (courseId != 0)
            {
                course_price = course_price.Where(s => s.Course_Id.Equals(courseId));
                price = course_price.SingleOrDefault(s => s.Payment_Type.Equals("Monthly"));
            }
            if (price == null)
            {
                return null;
            }
            return price;
        }

        //get weekly installment details
        public Course_Price getWeekPrice(int courseId = 0)
        {
            Course_Price price = new Course_Price();
            var course_price = from p in db.Course_Price
                          select p;
            if (courseId != 0)
            {
                course_price = course_price.Where(s => s.Course_Id.Equals(courseId));
                price = course_price.SingleOrDefault(s => s.Payment_Type.Equals("Weekly"));
            }
            return price;
        }

        //
        // GET: /Course/

        public ActionResult Index()
        {
            return View(db.Courses.ToList());
        }

        //
        // GET: /Course/Details/5

        public ActionResult Details(int id = 0)
        {
            Course course = db.Courses.Find(id);
            if (course == null)
            {
                return HttpNotFound();
            }
            Course_Price weekPrice = getWeekPrice(id);
            ViewData["WeekPriceSmall"] = weekPrice.Recurring_Amount;
            return View(course);
        }

        //
        // GET: /Course/Units/5
        public ActionResult Units(int id = 0)
        {
            Course course = db.Courses.Find(id);
            if (course == null)
            {
                return HttpNotFound();
            }
            Course_Price weekPrice = getWeekPrice(id);
            ViewData["WeekPriceSmall"] = weekPrice.Recurring_Amount;
            return View(course);
        }

        //
        // GET: /Course/AddPrice

        public ActionResult AddPrice(int id = 0)
        {
            Course course = db.Courses.Find(id);
            if (course == null)
            {
                return HttpNotFound();
            }
            ViewData["courseID"] = id;
            return View();
        }

        //
        // POST: /Course/AddPrice
        //add payment details for course, each time can only add one payment for "Full", "Month" or "Week"
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult AddPrice(Course_Price course_price)
        {
            //get user input of payment options, "Full", "Month" or "Week"
            course_price.Payment_Type = Request.Form["PaymentType"];
            int id = 0;
            int.TryParse(Request.Form["courseID"], out id);
            course_price.Course_Id = id;
            //check if there is already a payment record has the same payment option as user input under a course
            var findP = from p in db.Course_Price
                          select p;
            findP = findP.Where(s => s.Course_Id.Equals(course_price.Course_Id));
            foreach (Course_Price item in findP) {
                if (item.Payment_Type.Equals(course_price.Payment_Type))
                {
                    ViewData["courseID"] = course_price.Course_Id;
                    ModelState.AddModelError("paymentRepeat", "There already exists a payment with the same payment option, if you want to edit it, please go to payment controller.");
                    return View(course_price);
                }            
            }
            //set default value if user input is null, then save to BD
            if (ModelState.IsValid)
            {
                if (course_price.Total_Recurrings == null)
                {
                    course_price.Total_Recurrings = 1;
                }
                if (course_price.Deposit == null)
                {
                    course_price.Deposit = 0;                
                }
                if (course_price.Discount == null)
                {
                    course_price.Discount = 0;
                }
                course_price.Created_By = 1;
                course_price.Created_Date = DateTime.Today.Date;
                db.Course_Price.Add(course_price);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(course_price);
        }

        //
        // GET: /Course/Create

        public ActionResult Create()
        {
            //generate dropdownlist of providers
            List<SelectListItem> ProviderItems = new List<SelectListItem>();
            ProviderItems.Add(new SelectListItem { Text = "International Career Institute (ICI)", Value = "International Career Institute (ICI)" });
            ProviderItems.Add(new SelectListItem { Text = "Online Courses Australia", Value = "Online Courses Australia" });
            ProviderItems.Add(new SelectListItem { Text = "Careerline Courses Australia", Value = "Careerline Courses Australia" });
            ViewData["providers"] = ProviderItems;
            return View();
        }

        //
        // POST: /Course/Create

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(Course course)
        {
            List<SelectListItem> ProviderItems = new List<SelectListItem>();
            ProviderItems.Add(new SelectListItem { Text = "International Career Institute (ICI)", Value = "International Career Institute (ICI)" });
            ProviderItems.Add(new SelectListItem { Text = "Online Courses Australia", Value = "Online Courses Australia" });
            ProviderItems.Add(new SelectListItem { Text = "Careerline Courses Australia", Value = "Careerline Courses Australia" });
            ViewData["providers"] = ProviderItems;
            //read provider info from user selection (returned by dropdownlist)
            course.Course_Provider = Request.Form["providers"];
            if (ModelState.IsValid)
            {
                db.Courses.Add(course);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(course);
        }

        //
        // GET: /Course/Edit/5

        public ActionResult Edit(int id = 0)
        {
            Course course = db.Courses.Find(id);
            if (course == null)
            {
                return HttpNotFound();
            }
            return View(course);
        }

        //
        // POST: /Course/Edit/5

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(Course course)
        {
            if (ModelState.IsValid)
            {
                db.Entry(course).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(course);
        }

        //
        // GET: /Course/Delete/5

        public ActionResult Delete(int id = 0)
        {
            Course course = db.Courses.Find(id);
            if (course == null)
            {
                return HttpNotFound();
            }
            return View(course);
        }

        //
        // POST: /Course/Delete/5

        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            Course course = db.Courses.Find(id);
            db.Courses.Remove(course);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }

    }
}